package data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

public class SerialComunication {

	private static final String PORT_NAME = "/dev/cu.usbmodem641";
	/** Milliseconds to block while waiting for port open */
	private static final int TIME_OUT = 2000;
	/** Default bits per second for COM port. */
	private static final int DATA_RATE = 9600;

	/** The streams to the port, and the port */
	private static InputStream input;
	private static OutputStream output;
	private static SerialPort serialPort;
	private static Thread threadIOSerial;

	private static boolean escribir;
	private static byte[] mensaje;

	public static void main(String[] args) {
		inicializarConnection();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try{
			String line = br.readLine();  
			while (line != null) {
				mensaje=(line+" ").getBytes();
				puedeEscribir();
				line = br.readLine();
			}
		}
		catch(IOException e){e.printStackTrace();}
	}

	@SuppressWarnings("rawtypes")
	public static void inicializarConnection(){

		CommPortIdentifier portId = null;
		Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

		while (portEnum.hasMoreElements()&&portId==null) 
		{
			CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
			if (PORT_NAME.equals(currPortId.getName())) portId = currPortId;
		}

		if (portId != null) 
		{

			try {
				serialPort = (SerialPort) portId.open("Comunicacion Serial", TIME_OUT);
				serialPort.setSerialPortParams(DATA_RATE,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
				output = serialPort.getOutputStream();
				input = serialPort.getInputStream();

				Runnable aEjecutar= new Runnable() {

					private String leido = "";

					@Override
					public void run() {
						while(true)
						{
							try {
								int fu= input.available();
								if(fu>0)
								{
									byte[] lol = new byte[fu];
									input.read(lol);
									leido += new String(lol);
									//TODO mejorar esto
									//if(leido.contains("lol"))
									//{
										System.out.println("<< << "+leido);
										leido="";
									//}
								}
								if(escribir){
									output.write(mensaje);
									escribir=false;
								}
							} 
							catch (IOException e) {e.printStackTrace();} 
						}
					}
				};

				threadIOSerial = new Thread(aEjecutar);
				threadIOSerial.start();
			} 
			catch (Exception e) {e.printStackTrace();}
		}
		else System.out.println("[-ERROR-] No se encontro el puerto de coumnicacion.");
	}

	public static void puedeEscribir() {
		escribir = true;
	}

	public static void setMensaje(byte[] mensajeP) {
		mensaje = mensajeP;
	}
}
